﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.OpenApi.Models;
using PesticideManage.API.Data;
using PesticideManage.API.Extensions.DependencyInjection;
using PesticideManage.API.Filters;
using PesticideManage.API.Services.Files.Extensions.DependencyInjection;
using PesticideManage.API.Services.JWT.Extensions.DependencyInjection;
using Shang.COSXML;
using Shang.COSXML.Extensions.DependencyInjection;
using Shang.Sms.Extensions.DependencyInjection;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers(options =>
{
    options.Filters.Add<ExceptionFilter>();
    //options.Filters.Add<SampleExceptionFilter>();
}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    //options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// 配置Serilog
//Log.Logger = new LoggerConfiguration()
//    .MinimumLevel.Debug() // 设置最低日志级别
//    .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {SourceContext} ({FilePath}:{LineNumber}) - {Message:lj}{NewLine:l}") // 配置输出模板，包括文件路径和行号
//    .CreateLogger();
//builder.Host.UseSerilog(); // 使用Serilog作为日志框架
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
//builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    #region 启用swagger验证功能
    // 添加Jwt令牌
    var openApiReference = new OpenApiReference
    {
        Type = ReferenceType.SecurityScheme,
        Id = JwtBearerDefaults.AuthenticationScheme
    };
    var securityScheme = new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        // 默认 Bearer 
        // Type = SecuritySchemeType.ApiKey,
        Scheme = JwtBearerDefaults.AuthenticationScheme,
        Reference = openApiReference,
        // BearerFormat = "JWT",
    };

    c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, securityScheme);

    var securityRequirement = new OpenApiSecurityRequirement
            {
                { securityScheme, Array.Empty<string>() }
            };
    c.AddSecurityRequirement(securityRequirement);
    //c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
    //{
    //    { "Bearer", new string[] { } }
    //}
    //);
    // 忽略过时属性
    c.IgnoreObsoleteActions();

    #endregion
    #region 添加文档注释
    //var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    //c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
    // var xmlPath = Path.Combine(AppContext.BaseDirectory, item);
    string[] files = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
    foreach (string item in files)
    {
        c.IncludeXmlComments(item);
    }
    #endregion
});

//builder.Services.AddDbContext<PesticideContext>(opt =>
//    opt.UseInMemoryDatabase("TodoList"));
#region DbContext
builder.Services.AddPesticideContext();
#endregion

builder.Services.AddCosXml(builder.Configuration.GetSection(CosXmlConfigOptions.Name));
#region 跨域
builder.Services.AddCors(option =>
option.AddDefaultPolicy(config =>
    config.AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod()
          //.WithExposedHeaders(new string[] { "WWW-Authenticate" })
          ));
#endregion

#region JWT 身份验证 
builder.Services.AddJwtBearerAuthentication(builder.Configuration);
#endregion
#region 文件
builder.Services.AddStoreService(builder.Configuration);
#endregion
#region 短信
builder.Services.AddSmsService();
#endregion

//builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseSwagger();
app.UseSwaggerUI();

if (app.Environment.IsDevelopment())
{
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        SeedData.Initialize(services);
    }
    app.UseExceptionHandler("/Error");
}
app.UseCors();

//app.UseHsts();
//app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append(
             "Cache-Control", "no-cache, no-store");
    }
});
app.UseAuthentication();
app.UseAuthorization();

//var provider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
//{
//    {".txt","application/octet-stream" }
//});
//app.UseStaticFiles(
//    new StaticFileOptions
//    {
//        OnPrepareResponse = ctx =>
//        {
//            //ctx.Context.Response.Headers.ContentDisposition
//            ctx.Context.Response.Headers.Append("access-control-expose-headers", "Content-Disposition");
//            ctx.Context.Response.Headers.Append(
//                 "Content-Disposition", "attachment; filename=");
//            // attachment
//            ctx.Context.Response.Headers.Append(
//                 "Content-Type", "text/plain");
//        },
//        FileProvider = new PhysicalFileProvider(
//        Path.Combine(builder.Environment.ContentRootPath, Config.FilePath)),
//        RequestPath = $"/{Config.FilePath}"
//        //ContentTypeProvider = provider,
//    }
//);

app.MapControllers().RequireAuthorization();

app.Run();
